package com.service.impl;

import com.common.contant.RestResponse;
import com.common.exception.TaoException;
import com.common.exception.TaoExceptionEnum;
import com.common.utils.BeanHelper;
import com.dao.mapper.CategoryMapper;
import com.dto.CategoryDTO;
import com.entity.Category;
import com.service.CategoryService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.List;
import java.util.Optional;

/**
 * @Author: sijunqiang
 * @Date: 2020/5/16 17:55
 * @Description:
 */
@Slf4j
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class CategoryServiceImpl implements CategoryService {


    private final CategoryMapper categoryMapper;

    /**
     * 根据父节点：查询分类情况
     */
    @Override
    public List<CategoryDTO> queryListByParent(Long pid) {

        //  根据对象查询数据
        Category category = new Category();
        category.setParentId(pid);

        // 创建条件
        Example example = new Example(Category.class);
        // 根据parentId查询
        example.createCriteria().andEqualTo("parentId", pid);
        //  根据id排序
        example.setOrderByClause("id");
        List<Category> categoryList = categoryMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(categoryList)) {
            log.info("商品分类不存在: categoryList:[{}]", categoryList);
            throw new TaoException(TaoExceptionEnum.CATEGORY_NOT_FOUND);
        }
        //转换数据
        return BeanHelper.copyWithCollection(categoryList, CategoryDTO.class);
    }


    /**
     * 根据分类的id集合 查询商品的分类info集合
     */
    public List<CategoryDTO> queryByIdList(List<Long> ids) {
        // 根据分类的id集合 获取商品的分类信息
        Optional<List<Category>> optional = Optional.ofNullable(categoryMapper.selectByIdList(ids));
        if (!optional.isPresent()) throw new TaoException(TaoExceptionEnum.CATEGORY_NOT_FOUND);
        //2 返回结果
        List<Category> categoryList = optional.get();
        return BeanHelper.copyWithCollection(categoryList, CategoryDTO.class);
    }


}
